package com.lucky.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;

/**
 * Created by pc on 2018/5/15.
 */

public class AESUtil {

    private final static String IV="1b234f5d67e8c90a";

    /**
     * AES加密解密，填充方式为CBC，补码为PKCS5Padding,注意密钥和偏移量必须是16个字节.
     *
     * @param encrypt true为加密，false为解密
     * @param data    待加密解密数据
     * @param key     加密解密密钥，必须16个字节
     * @param iv      偏移量，必须16个字节
     * @return 返回加密或解密后的数据
     */
    public static byte[] aes(boolean encrypt, byte[] data, byte[] key, byte[] iv) {
        if (data != null || key != null && iv != null && key.length == 16 && iv.length == 16) {
            SecretKeySpec spec = new SecretKeySpec(key, "AES");
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
                cipher.init(mode, spec, new IvParameterSpec(iv));
                return cipher.doFinal(data);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String encrypt(String seed, String cleartext)
            throws Exception {
        String pwd = getPwd(seed);
        byte[] rawKey = pwd.getBytes();
        byte[] result = encrypt(cleartext.getBytes(),rawKey);
        return toHex(result);
    }

    public static String decrypt(String seed, String encrypted)
            throws Exception {
        String pwd = getPwd(seed);
        byte[] rawKey = pwd.getBytes();

        byte[] enc = toByte(encrypted);

        byte[] result = decrypt( enc,rawKey);

        return new String(result);

    }



    private static byte[] encrypt(byte[] raw, byte[] encrypted) throws Exception {
        byte[] aes = aes(true, raw, encrypted, IV.getBytes());
        return aes;

    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted)
            throws Exception {

        byte[] aes = aes(false, raw, encrypted, IV.getBytes());
        return aes;

    }

    private static byte[] toByte(String hexString) {

        int len = hexString.length() / 2;

        byte[] result = new byte[len];

        for (int i = 0; i < len; i++)

            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                                        16).byteValue();

        return result;

    }

    private static String toHex(byte[] buf) {

        if (buf == null)

            return "";

        StringBuffer result = new StringBuffer(2 * buf.length);

        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }

        return result.toString();

    }

    private final static String HEX = "0123456789ABCDEF";

    private static String getPwd(String pwd) {
        String aesKey=System.getProperty("aes-key");
        if(aesKey==null){
            aesKey="luckymall2019_09";
        }
        if(null==pwd){
            pwd="";
        }
        pwd= Base64.encode(pwd+ aesKey).substring(0, 16);
        return pwd;
    }


    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }


    public static void main(String[] args) throws Exception {
        /**
         * 第一种
         */
        String content = "jQuery1102004463028747702191_1568953978105({\"q\":\"\",\"p\":false,\"bs\":\"\",\"csor\":\"0\",\"err_no\":0,\"errmsg\":\"\",\"g\":[{\"type\":\"his_normal\",\"sa\":\"h_1\",\"q\":\"林俊杰新歌\"},{\"type\":\"his_normal\",\"sa\":\"h_2\",\"q\":\"cordova 插件 测试\"},{\"type\":\"his_normal\",\"sa\":\"h_3\",\"q\":\"打包 android.json\"},{\"type\":\"his_normal\",\"sa\":\"h_4\",\"q\":\"服务器\"},{\"type\":\"his_normal\",\"sa\":\"h_5\",\"q\":\"responseBodyAdive\"},{\"type\":\"his_normal\",\"sa\":\"h_6\",\"q\":\"瑞幸推出「小鹿茶合伙人」计划,或将拆分小鹿茶为子公司\"}]})";
        String password = "12345678";
        String base64String = AESUtil.encrypt("luckymall2019lyy","欢迎来到王者ddd 耀");
        System.out.println(base64String);
        base64String = AESUtil.encrypt("luckymall2019lyy","欢迎来到王者ddd 耀");
        System.out.println(base64String);
        base64String = AESUtil.encrypt("luckymall2019lyy",content);
        System.out.println(base64String);

        String string = AESUtil.decrypt("luckymall2019lyy",base64String );
        System.out.println(string);
    }
}
